package com.avic.rong.activity.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.mine.BindPhoneActivity;
import com.avic.rong.activity.product.OnlineCServiceActivity;
import com.avic.rong.api.RegisterApi;
import com.avic.rong.api.SendCodeApi;
import com.avic.rong.api.mine.UpdateInterestApi;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.bean.login_register.RegisterBean;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.RegexUtils;
import com.avic.rong.utils.StatusBarUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.TimeCount;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.luck.picture.lib.dialog.CustomDialog;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import io.reactivex.disposables.Disposable;

//注册
public class RegisterActivity extends RxAppCompatActivity implements BGASwipeBackHelper.Delegate {


    public static String ARG_URL = "arg_url";

    @BindView(R.id.tv_find_pwd)
    TextView tv_find_pwd;

    public static final String ARG_COME = "come_from";
    @BindView(R.id.type_pwd_phone)
    EditText type_pwd_phone;
    @BindView(R.id.type_captcha_yzma)
    TextView type_captcha_yzma;

    @BindView(R.id.type_captcha)
    EditText type_captcha;
    @BindView(R.id.btn_register)
    Button mBtnRegister;
    @BindView(R.id.tv_not_findyzma)
    TextView tv_not_findyzma;
    @BindView(R.id.cb_user)
    CheckBox cb_user;


    private boolean countDownTimeEnd = true;
    private SendCodeApi sendCodeApi;
    private RegisterApi registerApi;
    private Disposable countDownDisposable;
    private SharedPreferencesUtil sharedPreferencesUtil;

    private static String comeFrom;
    private BGASwipeBackHelper mSwipeBackHelper;
    private InputMethodManager imm;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registerl);

        ButterKnife.bind(this);

        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, getResources().getColor(R.color.color_loginbg));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        if (getIntent() != null) {
            comeFrom = getIntent().getStringExtra(ARG_COME);
        }

        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(this);

        type_captcha.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                /*Toast.makeText(RegisterActivity.this, "变化:"+s+";"+start+";"+after+";"+count, Toast.LENGTH_SHORT).show();
                Log.i("Seachal:","变化:"+s+";"+start+";"+after+";"+count);*/
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                /*Toast.makeText(RegisterActivity.this, "变化:"+s+";"+start+";"+before+";"+count, Toast.LENGTH_SHORT).show();
                Log.i("Seachal:","变化:"+s+";"+start+";"+before+";"+count);*/
            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() >= 6) {
                    mBtnRegister.setBackgroundResource(R.drawable.common_main_jianbian_r20_green);
                    mBtnRegister.setTextColor(getResources().getColor(R.color.white));
                    mBtnRegister.setEnabled(true);
                } else {
                    mBtnRegister.setBackgroundResource(R.drawable.grey_login);
                    mBtnRegister.setTextColor(getResources().getColor(R.color.black_text));
                    mBtnRegister.setEnabled(false);
                }
//                Log.e("wcx", "afterTextChanged: "+s.length() );
            }
        });

        initSwipeBackFinish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.keep);

        cb_user.post(new Runnable() {
            @Override
            public void run() {
                Rect delegateArea = new Rect();
                CheckBox delegate = cb_user;
                delegate.getHitRect(delegateArea);
                // 扩大触摸区域矩阵值
                delegateArea.left -= 50;
                delegateArea.top -= 50;
                delegateArea.right += 50;
                delegateArea.bottom += 50;
                TouchDelegate expandedArea = new TouchDelegate(delegateArea, delegate);
                if (View.class.isInstance(delegate.getParent())) {
                    // 设置视图扩大后的触摸区域
                    ((View) delegate.getParent()).setTouchDelegate(expandedArea);
                }

            }
        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    private void registerUser() {

        String phone = type_pwd_phone.getText().toString().trim();
        // String pwdAgain = type_pwd_pwd_again.getText().toString().trim();
        String captcha = type_captcha.getText().toString().trim();

        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(captcha)) {
            Toast toast = Toast.makeText(this, "手机号和验证码不能为空", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        if (StringUtils.isEmpty(captcha) && !StringUtils.isEmpty(phone)) {
            Toast toast = Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        if (StringUtils.isEmpty(phone) && !StringUtils.isEmpty(captcha)) {
            Toast toast = Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            Toast toast = Toast.makeText(this, "手机号码格式不正确", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }

        registerApi = new RegisterApi(this, registerListener);
        registerApi.setArguments(phone, captcha);
        registerApi.setCancel(false);
        registerApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(registerApi);
    }


    private void sendCode() {

        if (!countDownTimeEnd) return;
        sendCodeApi = new SendCodeApi(this, sendCodeListener);

        String phone = type_pwd_phone.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            Toast toast = Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            Toast toast = Toast.makeText(this, "手机号码格式不正确", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        sendCodeApi.setArguments(phone, 1, SharedPreferencesUtil.SIGN);
        sendCodeApi.setCache(false);
        sendCodeApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(sendCodeApi);
    }


    private void timeOut() {
        TimeCount timeCount = new TimeCount(60000, 1000, type_captcha_yzma, false);
        timeCount.start();

    }


    HttpOnNextListener sendCodeListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {//成功
                timeOut();
            } else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }


    };


    HttpOnNextListener<BaseResultEntity> registerListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {//成功
                RegisterBean registerBean = (RegisterBean) baseResultEntity.getData();
                String token = registerBean.getToken();
                sharedPreferencesUtil.setLoginState(true);//登录状态
                sharedPreferencesUtil.setLogintoken(token);
                sharedPreferencesUtil.setUserId(registerBean.getUserId()+"");
                String upinter = sharedPreferencesUtil.getAsString("upinter", null);
                Intent intent = new Intent("android.intent.action.CART_BROADCAST");
                intent.putExtra("data", "refresh");
                LocalBroadcastManager.getInstance(RegisterActivity.this).sendBroadcast(intent);
                sendBroadcast(intent);
                if (!StringUtil.isEmpty(upinter)) {
                    updateInter(registerBean.getToken(), upinter);
                }
                if (registerBean.isBindingMobile()) {
                    if (!StringUtil.isEmpty(comeFrom)) {
                        if (comeFrom.equals("MinePageEvent")) {
                            EventBus.getDefault().postSticky(new MinePageEvent());
                            startActivity(goMain());
                        } else if (comeFrom.equals("CartListReloadEvent")) {
                            EventBus.getDefault().postSticky(new CartListReloadEvent());
                            startActivity(goMain());
                        }else if (comeFrom.equals("OnlineCServiceActivity")) {
                            startActivity(OnlineCServiceActivity.getIntent(RegisterActivity.this, ""));
                            finish();
                        } else {
                            finish();
                        }
                    } else {
                        finish();
                    }
                } else {
                    showDialog();
                }
            } else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    };

    private void updateInter(String token,String sb) {
        UpdateInterestApi updateInterApi = new UpdateInterestApi(this,updateInterListener );
        updateInterApi.setArgument(token,sb);
        HttpManager.getInstance().doHttpDeal(updateInterApi);
    }

    HttpOnNextListener<BaseResultEntity> updateInterListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
//            String data = (String) baseResultEntity.getData();
//            if (data.equals("CODE_SUCCESS")){
//               ToastTools.showPublicToast("第一次更新成功");
//            }
        }
    };

    private void showDialog() {
        CustomDialog customDialog = new CustomDialog(this, R.layout.bindphone_dialog);
        customDialog.show();
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setCancelable(false);

        customDialog.findViewById(R.id.tv_bind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BindPhoneActivity.queryIntent(RegisterActivity.this));
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().postSticky(new HomePageEvent());
            startActivity(goMain());
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.tv_user_protocol, R.id.tv_find_pwd, R.id.type_captcha_yzma, R.id.btn_register, R.id.img_return, R.id.rl_phone, R.id.rl_pwd, R.id.tv_not_findyzma})
    public void clickEvent(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.rl_pwd:
                startActivity(LoginActivity.queryIntent(this));
                finish();
                break;
            case R.id.img_return:
                if (!StringUtil.isEmpty(comeFrom)) {
                    if (comeFrom.equals("MinePageEvent") || comeFrom.equals("CartListReloadEvent")) {
                        EventBus.getDefault().postSticky(new HomePageEvent());
                        startActivity(goMain());
                    } else {
                        finish();
                    }
                } else {
                    EventBus.getDefault().postSticky(new HomePageEvent());
                    startActivity(MainActivity.queryIntent(RegisterActivity.this));
                    finish();
                }
                break;
            case R.id.rl_phone:
                startActivity(LoginPhoneActivity.queryIntent(this));
                finish();
                break;
            case R.id.tv_user_protocol:
                startActivity(UserProtocolActivity.queryIntent(RegisterActivity.this));
                break;
            case R.id.type_captcha_yzma://发送验证码
                sendCode();
                break;
            case R.id.btn_register://注册
                boolean checked = cb_user.isChecked();
                if (checked) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    registerUser();
                } else {
                    ToastTools.showPublicToast("请先同意用户协议");
                }
                break;
            case R.id.tv_find_pwd:

                boolean checked1 = cb_user.isChecked();
                if (checked1) {
                    cb_user.setChecked(false);
                } else {
                    cb_user.setChecked(true);
                }
               /* checkFlag = !checkFlag;
                if (checkFlag) {
                    Drawable drawableLeft = getResources().getDrawable(R.mipmap.xuanzhong);
                    tv_find_pwd.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
                    tv_find_pwd.setCompoundDrawablePadding(DensityUtils.dp2px(RegisterActivity.this, 3));
                } else {
                    Drawable drawableLeftNo = getResources().getDrawable(R.mipmap.zhifufangshi_kuang);
                    tv_find_pwd.setCompoundDrawablesWithIntrinsicBounds(drawableLeftNo, null, null, null);
                    tv_find_pwd.setCompoundDrawablePadding(DensityUtils.dp2px(RegisterActivity.this, 3));
                }*/
                break;
            case R.id.tv_not_findyzma:
                startActivity(NotGetCodeActivity.queryIntent(this));
                break;
        }
    }

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownDisposable != null && (!countDownDisposable.isDisposed())) {
            countDownDisposable.dispose();
        }
    }

    public static Intent getIntent(Context context, String comeFrom) {
        Intent intent = new Intent(context, RegisterActivity.class);
        intent.putExtra(ARG_COME, comeFrom);
        return intent;
    }


    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        return intent;
    }

    public Intent goMain(){
        Intent intent = MainActivity.queryIntent(this);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return intent;
    }

}
